<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/12
 * Time: 15:46
 */

namespace App\HttpController;

use App\Utility\HttpRequest;
use App\Utility\MTool;
use App\Utility\UUID;
use EasySwoole\Core\Swoole\Task\TaskManager;

class Game extends AbstractBase
{


    public function getRate()
    {

        $where = ['da_rate', 'xiao_rate', 'dan_rate', 'shuang_rate', 'two_star_rate'];
        $rate = [];
        $this->db->where('name', ['in' => $where]);
        $res = $this->db->get('settings');

        if (!empty($res)) {
            foreach ($res as $item => $v) {
                $rate[$v['name']] = $v['value'];
            }
        }
        unset($res);

        $this->success($rate);
    }

    public function getNewLotteryNumber()
    {
        $turn = $this->request()->getRequestParam('turn');

        $turn_int = substr($turn, 8);
        $this->db->where('round_qishu', $turn);
        $res = $this->db->getOne('game_round');

        if (!empty($res)) {
            if (!empty($res['round_result'])) {
                $round_turn['lottery_num'] = explode(',', $res['round_result']);
                $this->success($round_turn, 'success');
            }

        }
        $this->error([], '未获取到信息');
    }

    public function getCurrentRound()
    {
        $info = $this->getCurrentRoundInfo();
        if (!$info) {
            $this->error([], '获取期数信息失败');
            return false;
        }
        $round_curr_info = $info['round_info'];


        $current_round_id = $info['round_id'];
        $this->db->where('round_id', $current_round_id);
        $round_info = $this->db->getOne('round');

        $this->db->orderBy('round_id', 'desc');
        $last_round = $this->db->getOne('game_round');

        if (!empty($round_info)) {
            $data = [
                'round_period' => $info['round_period'] . $round_info['round_circle'],
                'round_circle' => $round_info['round_circle'],
                'start_time' => $round_curr_info['start_time'],
                'open_time' => $round_curr_info['open_time'],
                'stop_time' => $round_curr_info['stop_time'],
                'round_name' => '第 ' . date('Ymd') . $round_info['round_circle'] . ' 期',
                'left_time' => $round_curr_info['open_time'] - time(),
                'last_lottery' => MTool::handle_number($last_round['round_result']),
                'lottery_number' => explode(',', $last_round['round_result'])
            ];


            $this->success($data, '获取期数成功');
            return false;
        }
        $this->error([], '获取失败');
    }


    public function getNoticeList()
    {
        // 1 公告

        $list_content = [];
        $this->db->where('cid', 1);
        $list = $this->db->get('article');
        if (!empty($list)) {
            foreach ($list as $item => $value) {
                $list_content[] = [
                    'content' => $value['introduction']
                ];
            }
        }

        $this->success($list_content, '获取列表');

    }


    public function getRoomList()
    {
        $room_name = $this->request()->getRequestParam('room_name');

        if (!$room_name) {
            $this->db->where('room_name', '%' . $room_name . '%', 'like');
        }

        $round_info = $this->getCurrentRoundInfo();
        if (empty($round_info['round_info'])) {
            $str = '休眠中';

        } else {
            $str = $round_info['round_info']['round_circle'];
        }

        $cols = ['room_uuid', 'room_name', 'room_id'];
        $this->db->where('status', 1);
        $this->db->orderBy('room_id', 'asc');
        $room_list = $this->db->get('game_room', null, $cols);
        if (!empty($room_list)) {
            foreach ($room_list as $item => $value) {
                $list = \App\Sock\Logic\Game::selectRoomFd($value['room_uuid']);
                $room_list[$item]['clients'] = count($list);
                $room_list[$item]['round'] = $str;
            }
            $this->success($room_list);
        }
    }


    public function getLastLotteryList()
    {
        $cols = ['round_qishu,round_result,round_turn'];


        $list = [];
        $this->db->orderBy('round_id', 'desc');
        $list = $this->db->get('game_round', 15, $cols);

        if (!empty($list)) {
            foreach ($list as $item => $index) {
                $list[$item]['lottery_number'] = MTool::handle_number($index['round_result']);
                $list[$item]['round_circle'] = $index['round_qishu'];
                $this->db->where('round_circle', $index['round_turn']);
                $res = $this->db->getOne('round');
                $list[$item]['open_time'] = date('H:i', strtotime($res['round_open_time']));
            }

//            $this->success($list);
//            return false;

        }
        $this->success($list);


    }

    public function getCurrentLotteryNumber()
    {
        $param = $this->request()->getRequestParam();
//        $this->db->where('round_turn', $param['round_turn']);
        $this->db->where('round_qishu', 'desc');
        $r = $this->db->getOne('game_round');
        $code = $r['round_result'];

        $nums = explode(',', $code);

        $num['code'] = $nums;
        $this->success($num);
        // $this->
        // 请求接口


    }


    public function getBetLog()
    {

        $user_id = $this->member_info['user_id'];
        $this->db->where('user_id', $user_id);
        $this->db->orderBy('bl_id', 'desc');
        $res = $this->db->get('bet_log', 200);
        $list = [];
        if (!empty($res)) {
            $data = [];
            foreach ($res as $item => $value) {
                $data['round_turn'] = $value['round_turn'];
                if ($value['bet_type'] != 'two_star') {
                    $data['bl_id'] = $value['bl_id'];
                    $data['amount'] = $value['bet_amount'];
                    $data['status'] = MTool::getStatus($value);
                    switch ($value['bet_info']) {
                        case 'wan':
                            $data['info'] = '万位(' . MTool::getUnit($value['bet_type']) . ')';
                            break;
                        case 'qian':
                            $data['info'] = '千位(' . MTool::getUnit($value['bet_type']) . ')';
                            break;
                        case 'bai':
                            $data['info'] = '百位(' . MTool::getUnit($value['bet_type']) . ')';

                            break;
                        case 'shi':
                            $data['info'] = '十位(' . MTool::getUnit($value['bet_type']) . ')';
                            break;
                        case 'ge':
                            $data['info'] = '个位(' . MTool::getUnit($value['bet_type']) . ')';
                            break;

                    }

                } else {
                    $data['bl_id'] = $value['bl_id'];
                    $data['amount'] = $value['bet_amount'];
                    $data['status'] = MTool::getStatus($value);
                    $unit_arr = explode(',', $value['bet_data']);
                    $info_arr = explode(',', $value['bet_info']);

                    $str = '';

                    foreach ($unit_arr as $item => $val) {
                        $str .= $this->bet_unit[$val] . '(' . $info_arr[$item] . ')  ';
                    }
                    $data['info'] = $str;
                }
                $list[] = $data;
            }
        }

        $this->db->where('user_id', $user_id);

        $this->db->where('bet_result', 1);
        $r = $this->db->getValue('bet_log', 'sum(bet_res_amount)');


        $this->db->where('user_id', $user_id);
        $this->db->where('bet_result', 2);
        $f = $this->db->getValue('bet_log', 'sum(bet_amount)');


        $this->db->where('user_id', $user_id);
        $res = $this->db->getValue('bet_log', 'sum(bet_amount)');

        $bet_log['list'] = $list;
        $bet_log['bet_sum'] = ['total' => $res, 'win' => $r, 'lose' => $f];


        $this->success($bet_log, 'success');

    }


    public function addCommonBet()
    {
        $param = $this->request()->getRequestParam();
        $rs = $this->getCurrentRoundInfo();


        if ($rs) {
            $info = $rs['round_info'];
            $current_time = time();
            $open_time = $info['open_time'];
            if ($open_time - $current_time <= 60) {
                $this->error([], '倒计时60S内无法下注');
                return false;
            }

        } else {
            $this->error([], '当前不在开奖时间内！');
            return false;
        }
        $room_id = $param['room_id'];
        $user_id = $this->member_info['user_id'];
        $round_time = date('Ymd') . $info['round_circle'];

        $convert = function ($val) {
            $arr = [
                'small' => 'xiao',
                'big' => 'da',
                'double' => 'shuang',
                'single' => 'dan'
            ];
            return (!$arr[$val]) ? null : $arr[$val];

        };
        if (!empty($param['list'])) {

            $count = 0;
            foreach ($param['list'] as $item => $value) {
                foreach ($value as $item => $v) {
                    $count++;
                }
            }
            $amount = $this->coin_type[$param['coin_type']] * $count;
            $this->db->where('id', $this->member_info['user_id']);
            $user_info = $this->db->getOne('user');

            if (bcsub($user_info['coin'], $amount) < 0) {
                $this->error([], '金币数额不足，下注失败！');
                return false;
            }

            // 查找当前
//            $this->db->where('room_uuid', $room_id);
            $this->db->where('round_turn', $round_time);
            $this->db->orderBy('round_id', 'desc');
            $info = $this->db->getOne('game_round');

            foreach ($param['list'] as $item => $value) {
                foreach ($value as $o => $v) {
                    $this->db->where('bet_type', $item);
                    $this->db->where('bet_info', $o);
                    $this->db->where('room_uuid', $room_id);
                    $this->db->where('user_id', $user_id);
                    $this->db->where('round_turn', $round_time);
                    $res = $this->db->getOne('bet_log');
                    if (!empty($res)) {
                        $this->db->where('bl_id', $res['bl_id']);
                        $update = [
                            'bet_amount' => ($res['bet_amount'] + $this->coin_type[$param['coin_type']])
                        ];
                        $this->db->update('bet_log', $update);
                        $this->db->where('id', $this->member_info['user_id']);

                        $update = [
                            'coin' => $this->db->dec($this->coin_type[$param['coin_type']]),
                        ];

                        $this->db->update('user', $update);

                    } else {
                        $insert[] = [
                            'round_turn' => $round_time,
                            'user_id' => $this->member_info['user_id'],
                            'room_uuid' => $room_id,
                            'bet_type' => $item,
                            'bet_info' => $o,
                            'bet_amount' => $this->coin_type[$param['coin_type']],
                            'bet_rate' => $this->settings[($convert($item)) . '_rate'],
                            'bet_result' => 0,//0等待开奖，1中奖，2，未中奖
                            'create_time' => time(),
                            'year' => date('Y'),
                            'month' => date('m'),
                            'day' => date('d'),

                        ];
                    }
                }
            }

        }

        if (!empty($insert)) {
            $this->db->insertMulti('bet_log', $insert);

            //扣除相应金币
            $this->db->where('id', $this->member_info['user_id']);

            $update = [
                'coin' => $this->db->dec($this->coin_type[$param['coin_type']] * $count),
            ];

            $this->db->update('user', $update);
        }
        $this->success([], '插入成功');

    }

    public function addTwoStarBet()
    {
        $rs = $this->getCurrentRoundInfo();


        if ($rs) {
//            $info = $rs['round_info'];
            $info = $rs['round_info'];
            $current_time = time();
            $open_time = $info['open_time'];
            if ($open_time - $current_time <= 60) {
                $this->error([], '倒计时60S内无法下注');
                return false;
            }
        } else {
            $this->error([], '当前不在开奖时间内！');
            return false;
        }

        $round_time = date('Ymd') . $info['round_circle'];
        $param = $this->request()->getRequestParam();
        $array_list = [];
        $i = 0;
        $type = [];
        $one = false;
        $datas = $param['list'];
        ksort($datas);

        foreach ($datas as $item => $value) {
            $array_list[] = $value;
            $type[] = $item;
            $list[$item] = $value;
            if ($i == 2) {
                break;
            }
            $i++;
        }
        if ($i == 1) {
            $this->error([], '数据不正确');
            return false;
        }

//        $res = MTool::cartesian($array_list);
        $res = MTool::CartesianProduct($array_list);
        $count = count($res);
        $total_amount = $count * $param['price'];
        $this->db->where('id', $this->member_info['user_id']);
        $user_info = $this->db->getOne('user');


        if (bcsub($user_info['coin'], $total_amount) < 0) {
            $this->error($user_info, '金币数额不足，下注失败！');
            return false;
        }
        // 查找当前
        $this->db->where('round_turn', $round_time);
        $this->db->orderBy('round_id', 'desc');
        $info = $this->db->getOne('game_round');

        foreach ($res as $item => $value) {
            $insert[] = [
                'round_turn' => $round_time,
                'user_id' => $this->member_info['user_id'],
                'bet_type' => 'two_star',
                'bet_data' => implode(',', $type),
                'bet_info' => $value,
                'bet_amount' => $param['price'],
                'bet_rate' => $this->settings['two_star_rate'],
                'bet_result' => 0, //0等待开奖，1中奖，2，未中奖
                'year' => date('Y'),
                'month' => date('m'),
                'day' => date('d'),
                'create_time' => time(),
            ];
        }
        if (!empty($insert)) {
            $res = $this->db->insertMulti('bet_log', $insert);
            if ($res) {
                $this->success([], '插入成功');

                //扣除相应金币
                $this->db->where('id', $this->member_info['user_id']);

                $update = [
                    'coin' => $this->db->dec($count * $param['price']),
                ];

                $this->db->update('user', $update);
            } else {
                $this->error([], '插入失败');
            }
        }


    }

    protected function getOpenLottery($round_turn)
    {
        $this->db->where('name', 'open_token');
        $list = $this->db->getOne('settings');
        $token = $list['value'] ?: 'teb6b9e68536f635fk';
        $url = "http://a.apiplus.net/{$token}/cqssc-1.json";
        $res = new HttpRequest();
        $result = $res->request('get', $url);

        echo $result . PHP_EOL;
        $lottery_result = json_decode($result->getBody(), true);

//        print_r($lottery_result);
        $number = $lottery_result['data'][0]['opencode'];
        $round = $lottery_result['data'][0]['expect'];

        echo $round . PHP_EOL;

        if ($round_turn != $round) {
            return false;
        }
        if (!$number) {
            return false;
        } else {
        }
        return ['number' => $number, 'expect' => $round];
    }


    public function onRequest($action): ?bool
    {


        return parent::onRequest($action); // TODO: Change the autogenerated stub
    }


}